﻿using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class BackgroundFitter : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private Camera targetCamera;
    [SerializeField] private bool matchWidth = true;

    private RectTransform rectTransform;
    private Image backgroundImage;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        backgroundImage = GetComponent<Image>();

        if (targetCamera == null)
            targetCamera = Camera.main;
    }

    private void Start()
    {
        UpdateBackgroundSize();
    }

    public void UpdateBackgroundSize()
    {
        // 确保组件初始化
        if (backgroundImage == null)
            backgroundImage = GetComponent<Image>();

        if (backgroundImage.sprite == null)
        {
            Debug.LogWarning("Sprite not assigned to Background Image.", this);
            return;
        }

        Vector2 spriteSize = backgroundImage.sprite.bounds.size;
        float imageAspect = spriteSize.x / spriteSize.y;

        if (targetCamera == null)
            targetCamera = Camera.main;

        float cameraHeight = targetCamera.orthographicSize * 2;
        float cameraWidth = cameraHeight * targetCamera.aspect;
        Vector2 cameraSize = new Vector2(cameraWidth, cameraHeight);

        float widthRatio = cameraSize.x / spriteSize.x;
        float heightRatio = cameraSize.y / spriteSize.y;
        float scaleMultiplier = matchWidth ? widthRatio : heightRatio;

        rectTransform.sizeDelta = spriteSize * scaleMultiplier;

        rectTransform.anchorMin = Vector2.zero;
        rectTransform.anchorMax = Vector2.one;
        rectTransform.offsetMin = rectTransform.offsetMax = Vector2.zero;
    }

#if UNITY_EDITOR
    private void OnValidate()
    {
        if (Application.isPlaying) return;

        // 强制初始化组件
        if (backgroundImage == null)
            backgroundImage = GetComponent<Image>();

        if (backgroundImage == null || backgroundImage.sprite == null)
            return;

        UpdateBackgroundSize();
    }
#endif
}